<!DOCTYPE html>
<html lang="" class="loading">
<head><meta name="generator" content="Hexo 3.8.0">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title></title>
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="google" content="notranslate">
    
    
    <meta name="author" content="艾尔蓝德"> 
    
    <link rel="icon" type="image/x-icon" href="/img/favicon.png"> 
    <link rel="stylesheet" href="/css/diaspora.css">
</head>

<body class="loading">
  <div class="nav">
    <ul id="menu-menu" class="menu">
        
        <li class="pview menu-item menu-item-type-post_type menu-item-object-page">
            <a href="/about/" title="简介">简介</a>
        </li>
        
        <li class="pview menu-item menu-item-type-post_type menu-item-object-page">
            <a href="/taglist/" title="分类">分类</a>
        </li>
        
        <li class="pview menu-item menu-item-type-post_type menu-item-object-page">
            <a href="/demo/" title="Demo">Demo</a>
        </li>
        
    </ul>
  <ul class="menu menu-git">
    <li><a href="https://github.com/leitingx762" target="_blank">github</a></li>
    <li><a href="https://gitee.com/airgoo" target="_blank">gitee</a></li>
    <li><a href="https://weibo.com/u/2100563617" target="_blank">微博</a></li>
  </ul>
    <p id="copyright">
        &copy; 2019 艾尔的小窝，
        Powerd By：<a href="http://hexo.io/" title="Hexo" target="_blank" rel="noopener">Hexo</a>
    </p>
</div>
<div id="header">
  <div>
    <a class="image-logo" href="/"></a>
    <div class="icon-menu switchmenu"></div>
  </div>
</div>

  <div id="top" style="display: block;">
<audio id="audio" loop="1" preload="auto" controls="controls" data-autoplay="false">
                <source type="audio/mpeg" src>
            </audio>
            
                <ul id="audio-list" style="display:none">
                    
                        <li title="0" data-url="http://link.hhtjim.com/163/5146554.mp3"></li>
                    
                        <li title="1" data-url="http://link.hhtjim.com/qq/001faIUs4M2zna.mp3"></li>
                    
                </ul>
            
    <div class="bar" style="width: 0;"></div>
    <a class="icon-left image-icon" href="javascript:history.go(-1)" data-url></a>
    <a class="icon-home image-icon" href="/"></a>
    <div title="播放/暂停" class="icon-play"></div>
    <h3 class="subtitle">Vue-Router : 《前传》</h3>
    <div class="social">
        <!--<div class="like-icon">-->
            <!--<a href="javascript:;" class="likeThis active"><span class="icon-like"></span><span class="count">76</span></a>-->
        <!--</div>-->
        <div>
            <div class="share">
                <a title="获取二维码" class="icon-scan" href="javascript:;">艾尔&nbsp;</a>
            </div>
            <div id="qr"></div>
        </div>
    </div>
    <div class="scrollbar"></div>
    <div class="scrollbar-mask"></div>
</div>

  <span id="config-title" style="display:none">艾尔的小窝</span>
  <div id="loader"></div>
  <div id="single">
    <div id="top" style="display: block;">
<audio id="audio" loop="1" preload="auto" controls="controls" data-autoplay="false">
                <source type="audio/mpeg" src>
            </audio>
            
                <ul id="audio-list" style="display:none">
                    
                        <li title="0" data-url="http://link.hhtjim.com/163/5146554.mp3"></li>
                    
                        <li title="1" data-url="http://link.hhtjim.com/qq/001faIUs4M2zna.mp3"></li>
                    
                </ul>
            
    <div class="bar" style="width: 0;"></div>
    <a class="icon-left image-icon" href="javascript:history.go(-1)" data-url></a>
    <a class="icon-home image-icon" href="/"></a>
    <div title="播放/暂停" class="icon-play"></div>
    <h3 class="subtitle">Vue-Router : 《前传》</h3>
    <div class="social">
        <!--<div class="like-icon">-->
            <!--<a href="javascript:;" class="likeThis active"><span class="icon-like"></span><span class="count">76</span></a>-->
        <!--</div>-->
        <div>
            <div class="share">
                <a title="获取二维码" class="icon-scan" href="javascript:;">艾尔&nbsp;</a>
            </div>
            <div id="qr"></div>
        </div>
    </div>
    <div class="scrollbar"></div>
    <div class="scrollbar-mask"></div>
</div>

    <div class="section">
        <div>
<div class="article">
    <div class="main">
        <h1 class="title">Vue-Router : 《前传》</h1>
        <div class="stuff">
            <span>3月 08, 2019</span>
            
  <ul class="post-tags-list"><li class="post-tags-list-item"><a class="post-tags-list-link" href="/tags/Vue/">Vue</a></li><li class="post-tags-list-item"><a class="post-tags-list-link" href="/tags/Vue-Router/">Vue-Router</a></li><li class="post-tags-list-item"><a class="post-tags-list-link" href="/tags/学习/">学习</a></li><li class="post-tags-list-item"><a class="post-tags-list-link" href="/tags/萌新的自我修养/">萌新的自我修养</a></li></ul>


        </div>
        <div class="content markdown">
            <h1 id="彻底搞懂路由跳转：location-和-history-接口"><a href="#彻底搞懂路由跳转：location-和-history-接口" class="headerlink" title="彻底搞懂路由跳转：location 和 history 接口"></a>彻底搞懂路由跳转：location 和 history 接口</h1><p>在单页应用中，通常由前端来配置路由，根据不同的 url 显示不同的内容。想要知道这是如何做到的，首先得了解浏览器提供的两大 API：<br><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="selector-tag">window</span><span class="selector-class">.location</span>：</span><br><span class="line"><span class="selector-tag">-</span> <span class="selector-tag">location</span><span class="selector-class">.href</span></span><br><span class="line"><span class="selector-tag">-</span> <span class="selector-tag">location</span><span class="selector-class">.hash</span></span><br><span class="line"><span class="selector-tag">-</span> <span class="selector-tag">location</span><span class="selector-class">.search</span></span><br><span class="line"><span class="selector-tag">-</span> <span class="selector-tag">location</span><span class="selector-class">.pathname</span></span><br><span class="line"><span class="selector-tag">-</span></span><br><span class="line"><span class="selector-tag">window</span><span class="selector-class">.history</span>：</span><br><span class="line"><span class="selector-tag">-</span> <span class="selector-tag">history</span><span class="selector-class">.pushState</span>()</span><br><span class="line"><span class="selector-tag">-</span> <span class="selector-tag">history</span><span class="selector-class">.replaceState</span>()</span><br><span class="line"><span class="selector-tag">-</span> <span class="selector-tag">history</span><span class="selector-class">.go</span>()</span><br><span class="line"><span class="selector-tag">-</span> <span class="selector-tag">history</span><span class="selector-class">.back</span>()</span><br><span class="line"><span class="selector-tag">-</span> <span class="selector-tag">history</span><span class="selector-class">.forward</span>()</span><br></pre></td></tr></table></figure></p>
<h2 id="window-location"><a href="#window-location" class="headerlink" title="window.location"></a>window.location</h2><p>我们先了解 location 对象，location 有很多的属性。我们可以通过改变其属性值修改页面的 url。我们在单页应用中需要做到的是改变 url 不刷新页面，location 接口提供以下两种方式可以做到：</p>
<ol>
<li><p><code>location.href</code> 赋值时只改变 url 的 hash<br><img src="./Vue-Router-前传/1.png" alt></p>
</li>
<li><p>直接赋值 <code>location.hash</code><br><img src="./Vue-Router-前传/2.png" alt></p>
</li>
</ol>
<p>而上面的列出其余两个属性 <code>location.search</code> 会直接刷新页面，这个就不解释了。但 location.pathname 照道理来说只改变 hash 应该是可以的，但实际上浏览器会编码这个属性值，所以无法直接赋带 # 号的值。</p>
<h2 id="window-history"><a href="#window-history" class="headerlink" title="window.history"></a>window.history</h2><p><a href="https://developer.mozilla.org/zh-CN/docs/Web/API/History" target="_blank" rel="noopener">history 接口</a>是 HTML5 新增的，它有五个方法可以改变 url 而不刷新页面。</p>
<p><code>history.pushState()</code><br><img src="./Vue-Router-前传/3.png" alt><br><code>history.replaceState()</code><br><img src="./Vue-Router-前传/4.jpg" alt><br><code>history.go()</code><br><img src="./Vue-Router-前传/5.jpg" alt></p>
<p>上面只演示了三个方法，因为 <code>history.back()</code> 等价于 <code>history.go(-1)</code>，<code>history.forward()</code> 则等价于 <code>history.go(1)</code>，这三个接口等同于浏览器界面的前进后退。</p>
<h2 id="如何监听-url-的变化"><a href="#如何监听-url-的变化" class="headerlink" title="如何监听 url 的变化"></a>如何监听 url 的变化</h2><p>现在我们已经知道如何不刷新页面改变页面的 url。虽然页面没刷新，但我们要改变页面显示的内容。这就需要 js 监听 url 的变化从而达到我们的目的。</p>
<p>我们有两个事件可以监听 url 的改变：</p>
<ol>
<li><h3 id="hashchange"><a href="#hashchange" class="headerlink" title="hashchange"></a>hashchange</h3><code>hashchange</code> 事件能监听 url hash 的改变。<br>先要加上<code>hashchange</code>事件监听的代码：<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">window</span>.addEventListener(<span class="string">'hashchange'</span>, <span class="function"><span class="params">e</span> =&gt;</span> <span class="built_in">console</span>.log(e))</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p>然后就可以在页面的 console 里愉快的实验了：<br><img src="./Vue-Router-前传/6.jpg" alt><br>从上图中我们可以知道不管是通过 location 接口直接改变 hash，还是通过 history 接口前进后退（只是 hash 改变的情况下），我们都可以监听到 url hash 的改变。但这个事件也只能监听 url hash 的变化。所以我们需要一个更强大的事件：<code>popstate</code>。</p>
<ol start="2">
<li><h3 id="popstate"><a href="#popstate" class="headerlink" title="popstate"></a>popstate</h3><a href="https://developer.mozilla.org/zh-CN/docs/Web/Events/popstate" target="_blank" rel="noopener">popstate</a> 事件能监听除 <code>history.pushState()</code> 和 <code>history.replaceState()</code> 外 url 的变化。</li>
</ol>
<p>先加上<code>popstate</code>事件监听的代码：<br><figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">window</span>.addEventListener(<span class="string">'popstate'</span>, <span class="function"><span class="params">e</span> =&gt;</span> <span class="built_in">console</span>.log(e))</span><br></pre></td></tr></table></figure></p>
<p>然后又可以在页面的 console 里愉快的实验了：<br><img src="./Vue-Router-前传/7.jpg" alt><br>其实不止 <code>history.pushState()</code> 和 <code>history.replaceState()</code> 对 url 的改变不会触发 <code>popstate</code> 事件，当这两个方法只改变 url hash 时也不会触发 hashchange 事件。</p>
<h2 id="hash-模式和-history-模式"><a href="#hash-模式和-history-模式" class="headerlink" title="hash 模式和 history 模式"></a>hash 模式和 history 模式</h2><p>我们都知道单页应用的路由有两种模式：hash 和 history。</p>
<ul>
<li><h3 id="hash-模式"><a href="#hash-模式" class="headerlink" title="hash 模式"></a>hash 模式</h3>如果我们不使用 <code>history.pushState()</code> 和 <code>history.replaceState()</code> 方法，我们就只需要在 <code>hashchange</code> 事件回调里编写 url 改变时的逻辑就行了。</li>
<li><h3 id="history-模式"><a href="#history-模式" class="headerlink" title="history 模式"></a>history 模式</h3>我们不仅要在 popstate 事件回调里处理 url 的变化，还需要分别在 <code>history.pushState()</code> 和 <code>history.replaceState()</code> 方法里处理 url 的变化。而且 history 模式还需要后端的配合，不然用户刷新页面就只有 404 可以看了?</li>
</ul>
<p>所以 hash 模式下我们的工作其实是更简单的，但为什么现在都推荐用 history 模式呢？总不是 hash 模式下的 url 太丑了，毕竟这是个看脸的世界?</p>
<p>不过 vue-router 在浏览器支持 <code>pushState()</code> 时就算是 hash 模式下也是用 <code>history.pushState()</code> 来改变 url，不知道有没什么深意？还有待研究…</p>
<hr>
<p style="text-align:right">转自：<a href="https://segmentfault.com/a/1190000014120456" target="_blank" rel="noopener">hugo_seth</a></p>
            <!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->
        </div>
        <ul id="pager" class="article">
          
            <li class="previous">
                <a href="/posts/learn/Babel-7-初识.html" data-original-title>← Babel-7：《初识》</a>
            </li>
          
          
            <li class="next">
                <a href="/posts/life/Blog开坑.html" data-original-title>《萌新的日常》-开坑记&lt;(￣︶￣)&gt;  →</a>
            </li>
          
        </ul>
    </div>
    
        <div class="side">
            <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#彻底搞懂路由跳转：location-和-history-接口"><span class="toc-number">1.</span> <span class="toc-text">彻底搞懂路由跳转：location 和 history 接口</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#window-location"><span class="toc-number">1.1.</span> <span class="toc-text">window.location</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#window-history"><span class="toc-number">1.2.</span> <span class="toc-text">window.history</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#如何监听-url-的变化"><span class="toc-number">1.3.</span> <span class="toc-text">如何监听 url 的变化</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#hashchange"><span class="toc-number">1.3.1.</span> <span class="toc-text">hashchange</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#popstate"><span class="toc-number">1.3.2.</span> <span class="toc-text">popstate</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#hash-模式和-history-模式"><span class="toc-number">1.4.</span> <span class="toc-text">hash 模式和 history 模式</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#hash-模式"><span class="toc-number">1.4.1.</span> <span class="toc-text">hash 模式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#history-模式"><span class="toc-number">1.4.2.</span> <span class="toc-text">history 模式</span></a></li></ol></li></ol></li></ol>
        </div>
    
</div>

  <div class="article">
    <div id="comments">
    <div id="vcomment" class="comment"></div>
    <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
    <script src="//cdn.jsdelivr.net/npm/valine/dist/Valine.min.js"></script>
    <script>
    setTimeout(function(){new Valine({
        el: '#vcomment',
        notify: 'true',
        verify: 'true',
        app_id: "E4EBrYgyq96lCpJpkLv3ocNg-9Nh9j0Va",
        app_key: "4SyMSBx4cpGeujpQBr0MhtCJ",
        placeholder: "留个言呗 (⁄ ⁄•⁄ω⁄•⁄ ⁄)",
        avatar: "mp"
      })},0)

    </script>
</div>
  </div>

</div>
    </div>
</div>

  <script src="//lib.baomitu.com/jquery/1.8.3/jquery.min.js"></script>
<script src="/js/plugin.js"></script>
<script src="/js/diaspora.js"></script>
<link rel="stylesheet" href="/photoswipe/photoswipe.css">
<link rel="stylesheet" href="/photoswipe/default-skin/default-skin.css">
<script src="/photoswipe/photoswipe.min.js"></script>
<script src="/photoswipe/photoswipe-ui-default.min.js"></script>

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>
    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">
        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>
        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">
            <div class="pswp__top-bar">
                <!--  Controls are self-explanatory. Order can be changed. -->
                <div class="pswp__counter"></div>
                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
                <button class="pswp__button pswp__button--share" title="Share"></button>
                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                      <div class="pswp__preloader__cut">
                        <div class="pswp__preloader__donut"></div>
                      </div>
                    </div>
                </div>
            </div>
            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div> 
            </div>
            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>
            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>
        </div>
    </div>
</div>

</body>
</html>